package com.example.storage;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.content.Context;

public class Storage {
	
	/***
	 * Save the array located in Setting
	 * @param context, the context where the function is called
	 * @param array, the array located in the setting object
	 */
	public static void save(Context context, int[] array){
		String filename = "save";
		FileOutputStream outputStream;
		
		File file = context.getFileStreamPath(filename);
		if(file.exists())
			file.delete();

		try {
		  outputStream = context.openFileOutput(filename, Context.MODE_APPEND);
		  for (int s : array) {
		      outputStream.write(String.valueOf(s).getBytes());
		      outputStream.write("\n".getBytes());
		  } 
		  outputStream.close();
		} catch (Exception e) {
		  e.printStackTrace();
		}
	}
	
	/***
	 * Check if file exists
	 * @param context, the context where the function is called
	 * @return
	 */
	public static boolean fileExists(Context context){
		String filename = "save";
		File file = context.getFileStreamPath(filename);
		if(!file.exists())
			return false;
		else 
			return true;

	}
	
	/***
	 * load the array stored in the file
	 * @param context, the context where the function is called
	 * @return the array
	 */
	public static int[] load(Context context){
		
		String filename = "save";
		int [] ret;
		InputStream inputStream = null;
		int i=0;
		ret = new int[20];
		
		try {
			inputStream = context.openFileInput(filename);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receive;

            try {
            	while ((receive = bufferedReader.readLine()) != null) {
                  ret[i]=Integer.parseInt(receive);
                  i++;
                  
                }
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

            try {
				inputStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        
		return ret;
	}
}
